var calCont = $empty();
var monthCont = $empty();
var actualMonth = $empty();
var selWrap = $empty();
var selCont = $empty();
var selSub = $empty();
var sf = $empty();
var selH = $empty();
var scrollLetter = $empty();
var selSearch = $empty();
var selPanelBack = $empty();

var setSelCont = function(content){	
	selCont.empty();
	scrollLetter.empty();
	selSearch.hide();
	toggleSelSub(1);
	if(selCont.st && (typeof selCont.st.tip.destroy == 'function'))
		selCont.st.tip.destroy();
				
	if($type(content) != 'array' || !content.length)
		return false;
		
	var scrollEv = function(){};
	var tips = new Tips({className: 'Tips'});
	var dl = new Element('dl');
 	var series = false;
	content.each(function(item){	
		var dt = new Element('dt');
		
		var id = (item.series != null) ? item.series.id : item.id; 
		var name = (item.series != null) ? item.series.seriesname : item.seriesname;
		if(name){
			var rightcont = new Element('div', {'class' : 'rightcont'}).inject(dt).hide();
			if(userstatus.isLoggedin){
				chk = new Element('input', {'type':'checkbox', 'checked' : ((item.checked) ? 'checked' : ''), 'value' : id});
				var lbl = new Element('label',{'rel' : 'Sorozat követése', 'class' : 'middle'});
				tips.attach(lbl);
				chk.inject(lbl);
				lbl.inject(rightcont);
			}
						
			dt.addEvent('mouseenter', function(){
				if(userstatus.isLoggedin || item.series != null)
					rightcont.show();
			});
			dt.addEvent('mouseleave', function(){
				if(userstatus.isLoggedin || item.series != null)
					rightcont.hide();
			});
			
			div = new Element('div').inject(dt);
			var a = new Element('a',{text: name}).inject(div);
			
			if(item.series == null)
			{
				seText = (item.firstaired != null && item.firstaired != '0000-00-00') ? '/' + new Date().parse(item.firstaired).format('%Y') + '/' : '';
				span = new Element('span', {text: seText}).inject(dt);
			}
			else {
				series = true;
				var epText = item.seasonnumber + 'x' + sprintf('%02d', item.episodenumber.toInt()) + ' ' + item.episodename;
				
				span = new Element('span', {text: epText}).inject(dt);
				if(item.firstaired != null && item.firstaired != '0000-00-00' && ((userstatus.preferences.original_date && new Date().parse(item.firstaired).get('time') < new Date().clearTime()) || (!userstatus.preferences.original_date && new Date().parse(item.firstaired).get('time') < new Date().increment('day', 1).clearTime())))
				{
					if(userstatus.preferences.show_caption)
					{
						var subt = new Element('a', {'class' : 'subt', 'html' : 'Felirat keres&eacute;se', rel: 'Felirat keres&eacute;se', href: 'http://felirat.mitnezel.net/#' + escape( name + ' ' + item.seasonnumber + 'x' + sprintf('%02d', item.episodenumber.toInt())) }).inject(span, 'top'); //subtitle
						tips.attach(subt);
					
						subt.addEvent('click', function(e){
							e.preventDefault();
						
							new MUI.Window({
								title: 'Van már felirat?',
								width: 680,
								height: 480,
								loadMethod: 'iframe',
								contentURL: subt.get('href')
							});
						});
					}
					if(userstatus.preferences.show_torrent)
					{
						var tor = new Element('a', {'class' : 'torr', 'html' : 'Torrent keres&eacute;se', rel: 'Torrent keres&eacute;se', 'href' : '#'}).inject(span, 'top');
						tips.attach(tor);
						tor.addEvent('click', function(e){
							e.preventDefault();
							fillTorrents.run(null, item);
							toggleSelSub();
						});
					}
				}
				
				if(item.overview != null && item.overview.length != 0){
					if(item.filename != null)
						img = '<img src="/image/episode/' + item.filename + '/150" alt="' + item.episodename + '" class="imageleft" />';
					else
						img = '';
					dt
						.setProperties({'title' : epText, 'rel' : img + item.overview + '<div class="clear"/></div>'}).addClass('tip');
				
				}
				if(lbl)
					lbl.removeClass('middle');
				
				var revIco = new Element('a',{
					'class' : 'reviewsIcon',
					'rel':'Vélemények',
					'text' : 'Vélemények',
					'href' : ('/e/' + name + "/" + item.seasonnumber + 'x' + sprintf('%02d', item.episodenumber.toInt()))
				}).inject(rightcont);
				tips.attach(revIco);
				if(!userstatus.isLoggedin)
					revIco.addClass('middle');	
			}
			
			div.addEvent('click',function(e){
				e.preventDefault();	
				new seriesPage(id, (item.seasonnumber) ? item.seasonnumber : null, (item.episodenumber) ? item.episodenumber.toInt() : null);		
				//MUI.seriesWindow(id, name, (item.seasonnumber) ? item.seasonnumber : null, (item.episodenumber) ? item.episodenumber.toInt() : null);			
			});
			
			dt.inject(dl);
		}
		
	});

	dl.inject(selCont);

	FancyForm.add($$('#' + selCont.get('id') + ' input[type=checkbox]'));
	selCont.st = new Tips.Pointy($$('#selMain dl dt.tip'),
	 {
		pointyTipOptions: {
			point: 3,
			width: 300,
			zIndex: 99,
			className: 'selPointy',
			offset: {x: 0, y: 0}
		}
	});
	
	$$('#' + selCont.get('id') + ' input[type=checkbox]').addEvent('click', function(){
    new Request({
        async: false,
        url: '/api/userseries.json|add|' + this.get('value')
    }).send();	
		loadTimeLine(false, false);
  });
	
	if(!series)
	{		
		selSearch.show();
		
		scrollEv = function(){
			var deep = dl.getScroll().y;
			var dtz = dl.getElements('dt');
			if(!dtz.length)
				return false;
			var oneh = dtz[0].getSize().y;
			var dttop = Math.floor(deep/oneh);
			if(!content[dttop])
				return false;
			var ltr = content[dttop].seriesname.replace(/^the /i, '').substr(0, 1).toUpperCase();
			var ltr = (/[a-zA-Z]/.test(ltr)) ? ltr : '#';
			scrollLetter.set('text', ltr);
		};
		
		scrollEv();
		
	}
	
	new ScScroller(dl, {
		onScroll: scrollEv
	});
	

};

var fillTorrents = function(){
	
	var addTorrents = function(json){
		selSub.empty();
		if(!json || !json.length)
		{
			new Element('span', {'class' : 'helpText', 'html' : 'Nincs tal&aacute;lat.'}).inject(selSub);
			return false;
		}
		var dl = new Element('dl');
		json.each(function(item){
			var dt = new Element('dt');
			var dv = new Element('div', {'class' : 'small'}).inject(dt);
			var a = new Element('a', {'html': item.title, 'href' : item.link}).inject(dv);
			var spn = new Element('span', {'html' : new Date().parse(item.pubDate).format('%Y.%m.%d %H:%M')}).inject(dt);
			dt.inject(dl);
		});
		dl.inject(selSub)
	};
	
		var sname = this.series.seriesname.replace(/\ ?\([^\)]+\)/, '');
		var uri = api + 'torrentsearch.json|' + sname;
		uri += ((this.firstaired != '0000-00-00') ? (userstatus.preferences.original_date) ? '|' + new Date().parse(this.firstaired).format('%Y-%m-%d') : '|' + new Date().parse(this.firstaired).decrement('day', 1).format('%Y-%m-%d') : '');
		uri += ((this.firstaired != '0000-00-00') ? (userstatus.preferences.original_date) ? '|' + new Date().parse(this.firstaired).increment('day', 1).format('%Y-%m-%d') : '|' + new Date().parse(this.firstaired).format('%Y-%m-%d') : '');
		
	new Request.JSON({
		url: uri,
		onRequest: function(){
			selWrap.addSpinner();
		},
		onComplete: function(){
			selWrap.removeSpinner();
		},
		onSuccess: addTorrents
	}).send();
	
};

var toggleSelSub = function(status)
{
	switch(status)
	{
		default:
			if(selCont.getStyle('left').toInt() == 0)
			{
				selCont.tween('left', -selCont.getSize().x);
				selSub.tween('left', 0);
				selPanelBack.show();
			}
			else {
				selCont.tween('left', 0);
				selSub.tween('left', selSub.getSize().x);
				selPanelBack.hide();
			}		
		break;
		
		case 1:
			selCont.setStyle('left', 0);
			selSub.setStyle('left', selSub.getSize().x);
			selPanelBack.hide();
		break;
		
		case 2:
			selCont.setStyle('left', -selCont.getSize().x);
			selSub.setStyle('left', 0);
			selPanelBack.show();
		break;
	}


};

var deActivate = function(){
	$$('#calMain dl.calCells dt').removeClass('active');
};

var loadCalendarKeys = function(){
	
	new Keyboard({
	    defaultEventType: 'keydown', 
	    events: { 
				'right' : function(e){	
					if(e.target.get('tag') == 'input')
						return true;
					else
						e.preventDefault();
					if(calCont.getElement('.calCells'))
					{					
						var cellCont = calCont.getElement('.calCells');
						if(calCont.getElement('.active'))
						{
							var active = calCont.getElement('.active');
							if(active.getNext('dt'))
								activateDay(active.getNext('dt'));
							else
							{
								var date = actualMonth.increment('month', 1);
								loadTimeLine(date, false, function(cellCont){
									var nextdate = new Date().parse(active.getProperty('date')).increment('day', 1).format('%Y-%m-%d');
									var nextday = cellCont.getElement('dt[date="' + nextdate + '"]');
									if(nextday)
										activateDay(nextday);
								});
							}	
								
						}
						else {
							activateDay(cellCont.getElement('dt'));
						}
					}
				},
				'left' : function(e){	
					if(e.target.get('tag') == 'input')
						return true;
					else
						e.preventDefault();
						
					if(calCont.getElement('.calCells'))
					{					
						var cellCont = calCont.getElement('.calCells');
						if(calCont.getElement('.active'))
						{
							var active = calCont.getElement('.active');
							if(active.getPrevious('dt'))
								activateDay(active.getPrevious('dt'));
							else
							{
								var date = actualMonth.decrement('month', 1);
								loadTimeLine(date, false, function(cellCont){
									var nextdate = new Date().parse(active.getProperty('date')).decrement('day', 1).format('%Y-%m-%d');
									var nextday = cellCont.getElement('dt[date="' + nextdate + '"]');
									if(nextday)
										activateDay(nextday);
								});
								
							}
						}
						else {
							activateDay(cellCont.getLast('dt'));
						}
					}
				},
				'up' : function(e){	
					if(e.target.get('tag') == 'input')
						return true;
					else
						e.preventDefault();
						
					if(calCont.getElement('.calCells'))
					{					
						var cellCont = calCont.getElement('.calCells');
						if(calCont.getElement('.active'))
						{
							var active = calCont.getElement('.active');
							if(active.getAllPrevious('dt').length > 5)
								activateDay(active.getAllPrevious('dt')[6]);
							else
							{
								var date = actualMonth.decrement('month', 1);
								loadTimeLine(date, false, function(cellCont){
									var nextdate = new Date().parse(active.getProperty('date')).decrement('day', 7).format('%Y-%m-%d');
									var nextday = cellCont.getElement('dt[date="' + nextdate + '"]');
									if(nextday)
										activateDay(nextday);
								});
								
							}
						}
						else {
							activateDay(cellCont.getLast('dt'));
						}
					}
				},
				'down' : function(e){	
					if(e.target.get('tag') == 'input')
						return true;
					else
						e.preventDefault();
						
					if(calCont.getElement('.calCells'))
					{					
						var cellCont = calCont.getElement('.calCells');
						if(calCont.getElement('.active'))
						{
							var active = calCont.getElement('.active');
							if(active.getAllNext('dt').length > 5)
								activateDay(active.getAllNext('dt')[6]);
							else
							{
								var date = actualMonth.increment('month', 1);
								loadTimeLine(date, false, function(cellCont){
									var nextdate = new Date().parse(active.getProperty('date')).increment('day', 7).format('%Y-%m-%d');
									var nextday = cellCont.getElement('dt[date="' + nextdate + '"]');
									if(nextday)
										activateDay(nextday);
								});
							}
						}
						else {
							activateDay(cellCont.getElement('dt'));
						}
					}
				}
	    }
	});
};

var loadTimeLine = function(date, activate, callback){
	
	date = ((date) ? '|' + date.format('%Y') + '|' + date.format('%m').toInt() : '');
	
	new Request.JSON({ url: api + 'calendar.json' + date,
		onRequest: function(){
			calCont.spin();
		},
		onSuccess: function(json, text){
			if(json)
			{
				setTimeline(json);
				if(typeof callback == 'function')
				{
					if(calCont.getElement('.calCells'))
						callback.run(calCont.getElement('.calCells'));
				}
			}
		},
		onComplete: function(){
			calCont.unspin();
		}
	}).send();
		
	var setTimeline = function(json){
		calCont.empty();
		setSelCont(null);
		if(json.date == new Date().format('%Y-%m-01'))
			$('thisMonth').fade('hide');
		else 
			$('thisMonth').fade('show');
				
		actualMonth = new Date().parse(json.date);
		
		monthCont.set('html', new Date.parse(json.date).format('%Y. %B'));
		
		var dl = new Element('dl', {'class' : 'calCells'});
		
		$H(json.caldays).each(function(item, key){
			var dt = new Element('dt');
			
			dt.store('content', item);
			dt.setProperty('date', key);
			if(key == new Date().format('%Y-%m-%d'))
				dt.addClass('celToday');
			
			if(actualMonth.format('%Y-%m') != new Date().parse(key).format('%Y-%m')){
				dt.addClass('celOtherMonth');
			}
			else {
				dt.addClass('celCurMonth');
			}
						
			dayNum = (new Date().parse(key).format('%d').toInt());
			
			new Element('span', {'class': 'day', text: dayNum}).inject(dt);
			var ul = new Element('ul').inject(dt);
			
			item.each(function(item, key){
				if(key < 4){
					sname = item.series.seriesname;
					if(sname.length > 12)
					 sname = sname.replace(/^(.{12})(.*)/i,"$1").trim() + '...';
					li = new Element('li', {text:sname}).inject(ul);
				}
								
			});
			c = item.length;
			if(c > 4) {
				c = c - 4;	
				li = new Element('li', {text:'még ' + c + '...'}).addClass('viewMore').inject(ul);
			}	
				
			dt.inject(dl);
		});
		
		dl.inject(calCont);
		setCalClicks();
	};
		
	var setCalClicks = function(){
		$$('#calMain dl.calCells dt').addEvents({
			'mousedown':function(e){
				e.preventDefault();
			},
			'click': function(e){
				e.preventDefault();
				clearSearch();		
				activateDay(this);
			}
		});
		today = $$('#calMain dl.calCells dt.celToday');
		activate = (activate == $empty()) ? true : activate;
		if(activate){
			if(today.length == 1){
				activateDay(today[0])
			}
			else {
				activateDay($$('#calMain dl.calCells dt.celCurMonth')[0]);
			}
		}
	};
	
};

var activateDay = function(el){
	if(!el)
		return false;
	$$('#calMain dl.calCells dt').removeClass('active');
	el.addClass('active');
	var content = el.retrieve('content');
	setSelCont(content);
	
	if(userstatus.userData && userstatus.userData.user_settings && userstatus.userData.user_settings.user_series && !userstatus.userData.user_settings.user_series.length && selCont && !selCont.get('text').length)
	{
		new Element('span', {'class' : 'helpText'}).inject(selCont).set('html', 'A sorozatok k&ouml;vet&eacute;s&eacute;hez el&#x151;sz&ouml;r ki kell v&aacute;lasztanod a sorozatokat.<br/>Ezt a fenti keres&#x151;, vagy a jobb fent tal&aacute;lhat&oacute; &bdquo;Folytat&oacute;d&oacute; &eacute;s k&ouml;vetett sorozatok&rdquo; ikonra kattintva megjelen&#x151; sorozat c&iacute;mek mellett tal&aacute;lhat&oacute; &bdquo;K&ouml;vet&eacute;s&rdquo; ikonra kattintva teheted meg.');
	}
	
};

var setNaviBtns = function(){
	
	$('prevMonth').addEvent('click', function(e){
		e.preventDefault();	

		var date = actualMonth.decrement('month', 1);
		loadTimeLine(date);
	});

	$('nextMonth').addEvent('click', function(e){
		e.preventDefault();		
		var date = actualMonth.increment('month', 1);
		loadTimeLine(date);
	});
	
	$('thisMonth').addEvent('click', function(e){
		e.preventDefault();		
		var date = new Date();
		loadTimeLine(date);
	});
	
	
};

var clearSearch = function(){
	sf.set('value', '');
	sf.blur();
	$('searchBtn').removeClass('searchClear');
};

var setSearchBar = function(){
	
	var obs = new Observer(sf, function(val, el){
		deActivate();
		
		if(val.length < 3){
			$('searchBtn').removeClass('searchClear');
			return setSelCont(null);
		}
		else {
			$('searchBtn').addClass('searchClear');
		}
			
		new Request.JSON({url: api + 'searchseries.json|' + $('searchSelect').get('value') + '|' + val,
			onRequest: function(){
				$('searchBtn').addClass('spinnerBlk');
			},
			onSuccess: function(json, text){
				setSelCont(json);
				if($type(json) != 'array' || !json.length)
					new Element('span', {'class' : 'helpText', 'html' : 'Nincs tal&aacute;lat.'}).inject(selCont);
			},
			onComplete: function(){
				(function(){$('searchBtn').removeClass('spinnerBlk');}).delay(500);
			}
		}).send();
	});
	
	sf.addEvent('keyup', function(e){
		if(e.key == 'esc'){
			clearSearch();
			setSelCont(null);
		}
	});
	
	$('searchBtn').addEvent('click', function(e){
		e.preventDefault();
		
		if(this.hasClass('searchClear')){
			clearSearch();
			setSelCont(null);			
		}
	});
	
	var FS = new FauxSelect($('searchSelect'), {triggerElement: $('searchBtn'),
		onChange: function(val, text){
			sf.setProperty('placeholder', 'Keresés: ' + text.toLowerCase() + '...');
		}
	});
	
};


var setContinuingBtn = function(){
	$('showContBtn').addEvent('click', function(e){
		e.preventDefault();
		clearSearch();
		new Request.JSON({url: api + 'continuing.json',
			onSuccess: function(json){
				setSelCont(json);
				selSearch.getElement('input').focus();
			}
		}).send();
		deActivate();		
	});
};

var setPanel2 = function(){
	$$('#mostPopularSeries a')
	.addEvent('click', function(e){
		e.preventDefault();
		var id = this.get('href').substr(1);
		var ttl = this.clone();
		var spn = ttl.getChildren('span');
		if(spn.length)
			spn[0].dispose();
		ttl = ttl.get('text');
		new seriesPage(id);
		//MUI.seriesWindow(id, ttl);
	});
	
};

var setSelSearch = function()
{
	var delknob = selSearch.getElement('a');
	var selInp = selSearch.getElement('input');
	delknob.addEvent('click', function(e){
		e.preventDefault();		
		
		var dl = selCont.getElement('dl');
		if(!dl)
			return;		
		var dts = selCont.getElements('dl > dt');
		if(!dts.length)
			return false;
		dts.show();
			
		selInp.set('value', '');
		selInp.blur();		
		dl.update();
		this.fade('hide');	
	});
	
	selInp.addEvent('keyup', function(e){
		var val = this.get('value');
		var dl = selCont.getElement('dl');
		if(!dl)
			return;
		var dts = selCont.getElements('dl > dt');
		if(!dts.length)
			return false;
		dts.show();
		
		if(val.length)
			delknob.fade('show');
		else
			delknob.fade('hide');
		
		switch(e.key)
		{
			default:
				if(!val.length)
				{
					dl.update();	
					return false;
				}
				dts.each(function(elem){
					if(!elem.getElement('a').get('text').toLowerCase().test(val))
						elem.hide();
				});
				dl.update();
			break;
			
			case 'esc':
				this.set('value', '');
				this.blur();
				dl.update();
				delknob.fade('hide');
			break;
		}
	});
	
	selPanelBack.addEvent('click', function(e){
		e.preventDefault();
		toggleSelSub();
	});
	
};

window.addEvent('domready', function(){
	calCont = $('calMain');
	monthCont = $('monthTitle');
	selWrap = $('selWrap');
	selCont = $('selMain');
	selSub = $('selSub');
	sf = $('searchField');
	selH = $('selHeader');
	scrollLetter = $('scrollLetter');
	selSearch = $('selSearch');
	selPanelBack = $('selPanelBack');
	
	userstatus = new updateUserStatus({
		onLogin: function(){
			$('showContBtn').fade('show');
		},
		onLogout: function(){
			$('showContBtn').fade('hide');
		},
		onOther: function(){
			loadTimeLine();
		}	
	});
	
	loadTimeLine();
	loadCalendarKeys();
	setNaviBtns();
	setSearchBar();

	setContinuingBtn();
	setPanel2();
	
	setSelSearch();
	
	new ScScroller($('recentReviewsCont'));
			
});

